package com.xz.disk.serviceimpl;

import com.xz.disk.entity.MyFile;
import com.xz.disk.service.FileService;
import com.xz.disk.utils.AppContext;
import com.xz.disk.utils.FileUtil;
import com.xz.disk.utils.ResponseResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description
 * @PACKAGE_NAME: com.xz.disk.serviceimpl
 * @NAME: FileServiceImpl [javaproject]
 * @author：ASUS 肖舟 XiaoZhou
 * @datetime 创建于： 2020/8/2 10:44 星期日
 */
@Service
public class FileServiceImpl implements FileService {

    @Value("${path.rootPath}")
    private String rootPath;


    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");




    @Override
    public ResponseResult list(String path) {

        try {
            path = myDecode(path);
//            System.err.println("文件列表路径是："+path);
            if (!FileUtil.exist(path)) {
                return ResponseResult.ERROR("路径不存在");
            }

            List<MyFile> fileList = new ArrayList<>();
            File file = new File(path);
            File[] files = file.listFiles();

            if(!ObjectUtils.isEmpty(files)){
                for (File f : files) {
                    MyFile myFile = getMyFile(f);
                    fileList.add(myFile);
                }
                return ResponseResult.SUCCESS("获取文件列表成功", fileList);
            }else{
                return ResponseResult.SUCCESS("没有文件", fileList);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.ERROR("获取文件列表失败");
    }

    public MyFile getMyFile(File f) {
        // 文件名
        String fileName = f.getName();
        // 文件后缀
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);

        // 大小
        double sizeNum = f.length() / 1024.0;
        String size = "";
        if (!f.isDirectory()) {
            if (sizeNum < 1024) {
                size = (double) Math.round(sizeNum * 100) / 100 + "KB";
            } else if (sizeNum / 1024.0 < 1024) {
                size = (double) Math.round((sizeNum / 1024.0) * 100) / 100 + "MB";
            } else if (((sizeNum / 1024.0) / 1024.0) < 1024) {
                size = (double) Math.round(((sizeNum / 1024.0) / 1024.0) * 100) / 100 + "GB";
            }
        } else {
            size = "-";
        }
        // 最后修改时间
        long lastModified = f.lastModified();
        String time = dateFormat.format(lastModified);
        // 是否是文件夹目录
        String isDirectory = f.isDirectory() ? "true" : "false";
        // 路径
        String url = f.getAbsolutePath();
        // 图标
        String icon = AppContext.getIcons().get(suffix);
        if(StringUtils.isEmpty(icon)){
            icon = "default.png";
        }
        if("true".equals(isDirectory)){
            icon = "directory.png";
        }
        if("jpg".equals(suffix) || "png".equals(suffix) || "jpeg".equals(suffix) || "gif".equals(suffix)){
            String str = f.getAbsolutePath().replace(File.separator,"^");
            try {
                str = java.net.URLEncoder.encode(str.replace(File.separator,"^"),"utf-8");
                icon = "/file/preview/"+str;
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

        }
        if("回收站".equals(fileName)){
            icon = "recycle_bin.png";
        }
        MyFile myFile = new MyFile(fileName, icon,url, size, time, isDirectory, suffix);
        return myFile;
    }

    @Override
    public ResponseResult mkdir(String path, String fileName) {
        return null;
    }

    @Override
    public ResponseResult touch(String path, String fileName) {
        return null;
    }

    @Override
    public ResponseResult writeText(String path, String content) {
        return null;
    }

    @Override
    public ResponseResult readText(String path) {
        try {
            path = path.replace("%5C%5C",File.separator).replace("%5C",File.separator);
            path = java.net.URLDecoder.decode(path,"utf-8");
            String str = FileUtil.readFile(path);
            return ResponseResult.SUCCESS("内容读取成功",str);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return ResponseResult.ERROR("读取失败");
        }
    }

    @Override
    public ResponseResult delete(String path) {
        return null;
    }

    @Override
    public ResponseResult clear() {
        return null;
    }

    @Override
    public ResponseResult move(String oldPath, String newPath) {
        return null;
    }

    @Override
    public ResponseResult eyeImage(String path) {
        return null;
    }

    @Override
    public ResponseResult upload() {
        return null;
    }

    @Override
    public ResponseResult download() {
        return null;
    }

    @Override
    public ResponseResult search(String fileName) {
        long time = System.currentTimeMillis();
        List<MyFile> list;
        list = new ArrayList<>();
        traverseFolder(rootPath, fileName, list);
        if (list.size() <= 0) {
            return ResponseResult.SUCCESS("搜索完毕，无搜索结果");
        }
        return ResponseResult.SUCCESS("搜索完毕，共"+ list.size()+ "项，用时" + ((System.currentTimeMillis() - time) / 1000.0) + "秒", list);
    }

    @Override
    public ResponseResult getFileListByType(String type) {
        long time = System.currentTimeMillis();
        List<MyFile> list = new ArrayList<>();
        traverseFolderByType(rootPath, type, list);
        return ResponseResult.SUCCESS("搜索完毕，共"+list.size()+"项,用时："+((System.currentTimeMillis()-time)/1000.0)+"秒",list);
    }


    // 按类型搜索的全盘遍历
    public void traverseFolderByType(String path, String type, List<MyFile> list) {
        File file = new File(path);
        if (file.exists()) {
            File[] files = file.listFiles();
            if (null == files || files.length == 0) {
//                System.out.println("文件夹是空的!");
                return;
            } else {
                for (File file2 : files) {
                    if (file2.isDirectory()) {
                        traverseFolderByType(file2.getAbsolutePath(), type, list);
                    } else {
//                        System.out.println("文件:" + file2.getAbsolutePath());
                        String fileName = file2.getName();

                        if (type.equals(getFileType(file2))) {
                            list.add(getMyFile(file2));
                        }
                    }
                }
            }
        } else {
            System.out.println("文件不存在!");
        }
    }

    // 搜索文件，的全盘遍历
    public void traverseFolder(String path, String searchContent, List<MyFile> list) {
        File file = new File(path);
        if (file.exists()) {
            File[] files = file.listFiles();
            if (null == files || files.length == 0) {
                return;
            } else {
                for (File file2 : files) {
                    if (file2.isDirectory()) {
                        traverseFolder(file2.getAbsolutePath(), searchContent, list);
                    } else {
                        String fileName = file2.getName();
                        if (fileName.toLowerCase().indexOf(searchContent.toLowerCase()) != -1) {
                            list.add(getMyFile(file2));
                        }
                    }
                }
            }
        } else {
            System.out.println("文件不存在!");
        }
    }

    String getFileType(File file){
        String suffix = file.getName().substring(file.getName().lastIndexOf(".")+1);
        String type = "";
        if("png".equals(suffix)||"jpg".equals(suffix)||"gif".equals(suffix)||"jpeg".equals(suffix)){
            type = "image";
        }else if("mp4".equals(suffix)||"3gp".equals(suffix)){
            type = "video";
        }else if("mp3".equals(suffix)||"ogg".equals(suffix) ||"wav".equals(suffix)){
            type = "audio";
        }else if("xls".equals(suffix)||"xlsx".equals(suffix)){
            type = "xls";
        }else if("doc".equals(suffix)||"docx".equals(suffix)){
            type = "doc";
        }else if("".equals(suffix)||"txt".equals(suffix)||"md".equals(suffix)){
            type = "txt";
        }else if("zip".equals(suffix)||"7z".equals(suffix)||"tar".equals(suffix)||"rar".equals(suffix)){
            type = "zip";
        }else{
            type="default";
        }
        return type;
    }


    private String myDecode(String path) {
        try {
            path = java.net.URLDecoder.decode(path, "utf-8");
            path = path.replace("%5C%5C", File.separator).replace("%5C", File.separator).replace("%255CC", File.separator).replace("^", File.separator);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return path;
    }

}
